package com.lazason.wib4android;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import weibo4andriod.Paging;
import weibo4andriod.User;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

public class FriendHomeActivity extends BasicActivity {
	ListView listView;
	Weibo weibo;
	String screen_name;
	ListViewAdapter adapter;
	List<weibo4andriod.Status> friendsTimeline = null;
	int page = 1;
	boolean isLoading = false;
	TimeLineTask timeLineTask;
	Paging paging;
	String userId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend);
		listView = (ListView) findViewById(R.id.friendweibo);
		paging = new Paging();
		paging.setPage(page);
		userId = this.getIntent().getStringExtra("id");
		screen_name = this.getIntent().getStringExtra("screen_name");
		if(screen_name==null){
		screen_name = this.getIntent().getData().getQueryParameter(
				"screen_name");
		}
		

		
		Log.d("FriendHomeActivity", " screen_name =" + screen_name);
		weibo = OAuthConstant.getInstance().getWeibo();
		Log.d("FriendHomeActivity",
				" weibo = OAuthConstant.getInstance().getWeibo();");
		listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

				if (totalItemCount != 0) {
					if (firstVisibleItem + visibleItemCount > (totalItemCount - 20)
							&& page < 101) {

						if (!isLoading) {

							isLoading = true;
							// 开线程去下载网络数据

							timeLineTask = new TimeLineTask();
							page++;
							timeLineTask.execute(page);
						}

					}

				}
			}

			@Override
			public void onScrollStateChanged(AbsListView paramAbsListView,
					int paramInt) {
				// TODO Auto-generated method stub

			}

		});

		FirstTimeLineTask task = new FirstTimeLineTask();
		Log.d("FriendHomeActivity", " FirstTimeLineTask ");
		task.execute();

	}

	private class FirstTimeLineTask extends
			AsyncTask<Void, Void, List<weibo4andriod.Status>> {

		protected List<weibo4andriod.Status> doInBackground(Void... arg) {
			if (userId!=null) {
				try {

					friendsTimeline = weibo.getUserTimeline(userId);

				} catch (WeiboException we) {
					we.printStackTrace();

				} catch (Exception e) {
					e.printStackTrace();

				}
				if(friendsTimeline!=null){
				return friendsTimeline;
				}
			}
			try {
				Log.d("FriendHomeActivity", URLEncoder.encode(screen_name,
						"utf-8"));

				friendsTimeline = weibo.getUserTimeline("screen_name="
						+ URLEncoder.encode(screen_name), true);

			} catch (WeiboException we) {
				we.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();

			}
			// 用中文昵称可能取不到timeline，这时需要用id来取timeline
			if (friendsTimeline == null || friendsTimeline.size() == 0) {
				try {

					String s = java.net.URLEncoder.encode(screen_name, "utf-8");
					Log.d("FriendHomeActivity", " weibo.showUser(s,true) ");
					User user = weibo.showUser(s, true);
					Log.d("FriendHomeActivity", "user id: " + user.getId());
					Log.d("FriendHomeActivity", "user name: " + user.getName());
					userId = String.valueOf(user.getId());
					friendsTimeline = weibo.getUserTimeline(userId);

				} catch (WeiboException we) {
					we.printStackTrace();

				} catch (Exception e) {
					e.printStackTrace();

				}
			}
			return friendsTimeline;
		}

		protected void onPostExecute(List<weibo4andriod.Status> friendsTimeline) {
			MyApplication.friend = new ArrayList<Map<String, Object>>();
			if (friendsTimeline == null || friendsTimeline.size() == 0) {
				Toast.makeText(getApplicationContext(), "没有找到此微博",
						Toast.LENGTH_SHORT).show();
				FriendHomeActivity.this.finish();
				isLoading = false;
				page = 1;
				return;
			}
			Log.d("FriendHomeActivity", "friendsTimeline length:"
					+ friendsTimeline.size());
			for (weibo4andriod.Status status : friendsTimeline) {

				Map<String, Object> map = new HashMap<String, Object>();

				map.put("profile", status.getUser().getProfileImageURL()
						.toString());
				map.put("weibo", status.getText());
				map.put("username", status.getUser().getName());
				map.put("id", status.getUser().getId());
				MyApplication.friend.add(map);

			}
			adapter = new ListViewAdapter(FriendHomeActivity.this,
					MyApplication.friend, R.layout.listitem, new String[] {
							"profile", "weibo", "username" }, new int[] {
							R.id.profile, R.id.weibo, R.id.username },listView);
			listView.setAdapter(adapter);
			isLoading = false;
			page = 1;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}

	private class TimeLineTask extends
			AsyncTask<Integer, Void, List<weibo4andriod.Status>> {

		protected List<weibo4andriod.Status> doInBackground(Integer... page) {
			List<weibo4andriod.Status> friendsTimeline = null;
			friendsTimeline = null;
			if (userId!=null) {
				try {

					System.out.println("page : " + page[0].intValue());
					paging.setPage(page[0]);

					friendsTimeline = weibo.getUserTimeline(userId, paging);

				} catch (WeiboException we) {
					we.printStackTrace();

				} catch (Exception e) {
					e.printStackTrace();

				}
				if(friendsTimeline!=null){
				return friendsTimeline;
				}
			}
			try {
				Log.d("FriendHomeActivity", URLEncoder.encode(screen_name,
						"utf-8"));
				paging.setPage(page[0]);
				friendsTimeline = weibo.getUserTimeline("screen_name="
						+ URLEncoder.encode(screen_name), paging, true);

			} catch (WeiboException we) {
				we.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();

			}
			
			return friendsTimeline;
		}

		protected void onPostExecute(List<weibo4andriod.Status> friendsTimeline) {
			if (friendsTimeline == null) {
				Toast.makeText(getApplicationContext(), "没有更多的微博",
						Toast.LENGTH_SHORT).show();
				isLoading = false;
				return;
			}

			for (weibo4andriod.Status status : friendsTimeline) {
				Map<String, Object> map = new HashMap<String, Object>();

				map.put("profile", status.getUser().getProfileImageURL()
						.toString());
				map.put("weibo", status.getText());
				map.put("username", status.getUser().getName());
				map.put("id", status.getUser().getId());
				MyApplication.friend.add(map);
			}

			// listView.removeFooterView(layout);

			adapter.notifyDataSetChanged();
			isLoading = false;

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}

}
